package com.apexsoft.front.common.utils;


import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

import org.apache.commons.codec.binary.Base64;

public class KeyUtil {
	
	private static Base64 base64=new Base64();

	public static PrivateKey getPrivateKey(String priKeyText) throws Exception{
		return getPrivateKey(priKeyText.getBytes());
	}
	
	public static PrivateKey getPrivateKey(byte[] priKeyText) throws Exception{
		PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(base64.decode(priKeyText));
		KeyFactory keyf = KeyFactory.getInstance("RSA");
		PrivateKey prikey = keyf.generatePrivate(priPKCS8);
		return prikey;
	}
	
	public static PublicKey getPublicKey(String pubKeyText) throws Exception{
		return getPublicKey(pubKeyText.getBytes());
	}
	
	public static PublicKey getPublicKey(byte[] pubKeyText) throws Exception{
		X509EncodedKeySpec bobPubKeySpec = new X509EncodedKeySpec(base64.decode(pubKeyText));
		KeyFactory keyFactory = KeyFactory.getInstance("RSA");
		PublicKey pubKey = keyFactory.generatePublic(bobPubKeySpec);
		return pubKey;
	}
}
